var common = require("../../utils/common.js");
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    index: -1, //第几条
    length: 10,
    total: 0, //共多少条
    adviserList: [],
    canIUse: false,
    loading: true,
    ls: false,
    forumImgList: ['../../img/banner.png', '../../img/banner.png', '../../img/banner.png'],
    currentTab: 0,
    indexs: '',
    allIndex: -1,
    forumType: -1,

    isInfo: false, //是资讯还是论坛
    bannerLists: "",
    indicatorDots: "",
    autoplay: "",
    interval: "",
    duration: "",
    swiperIndex: "",
    circular: "",
    selectIndex: 0, //资讯列表index
    isInfo1: true,
    variable: '', //滚动条的位置
    scrollTop: 0,
    isShow: false
  },
  swiperChange(e) {
    const that = this;
    that.setData({
      swiperIndex: e.detail.current,
    })
  },

  //滚动监听
  scroll: function (e) {
    var scrollTop = e.detail.scrollTop;
    var bannerHeight = this.data.bannerHeight;
    var selectIndex = this.data.selectIndex;
    var listMainHeight = this.data.listMainHeight;
    if (scrollTop >= bannerHeight) {
      this.setData({
        variable: e.detail.scrollTop - 3,
      })
    } else {
      this.setData({
        variable: ''
      })
    }
  },

  onLoad: function (options) {
    console.log("页面onload")
    var that = this;
    wx.setNavigationBarTitle({
      title: '论坛'
    });
    if (app.globalData.xcxshareid) {
      that.setData({
        xcxid: app.globalData.xcxshareid
      })
    }
    if (app.globalData.xcxtype.isShow == "1") {
      that.setData({
        isShow: true
      })
    } else {
      that.setData({
        isShow: false
      })
    }
    wx.hideTabBar();
    getApp().editTabBar();

  },

  onShow: function () {
    console.log("页面onShow")
    //进入论坛列表页，首先查询用户信息
    //需要bid:"", xcxOpenId: ''
    var that = this;
    that.setData({
      loading: true
    });

    wx.login({
      success: res => {
        if (res.code) {
          var code = res.code;
          //获取xcxOpenId;
          // 获取用户信息
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                console.log("已授权登录1");
                wx.getUserInfo({
                  success: function (res) {
                    console.log(res.userInfo)
                    app.globalData.userInfo = res.userInfo;
                    app.globalData.isFind = true;
                    that.getOpenId(code);
                  }
                })
              } else {
                //未授权登录
                console.log("未授权登录");
                app.globalData.isFind = false;
                that.getOpenId(code);
                that.setData({
                  loading: false,
                  canIUse: true
                })
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);
          that.setData({
            loading: true,
            ls: true
          })
        }
      }
    })
  },

  getOpenId: function (code) {
    var that = this;
    var xcxid = app.globalData.queryWlpXcxByParams[0].id
    common.ajaxPost(
      'portal/wlpUsers/getXcxOpenId.action', {
        // bid: app.globalData.bid,
        code: code,
        xcxId: xcxid
      },
      function (res) {
        if (res && res["result"]) {
          console.log(res);
          app.globalData.xcxOpenId = res.xcxOpenId;
          // that.findUser();
          if (app.globalData.isFind) {
            //已授权
            console.log("已授权2");
            that.findUser();
          } else {
            //未授权
          }
        }
      }
    )
  },


  openSetting: function (e) {
    //未授权的情况
    console.log(e);
    var that = this;
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      return false;
    } else {
      console.log(e.detail.userInfo);
      app.globalData.userInfo = e.detail.userInfo;
      //授权时查询用户
      that.setData({
        canIUse: false,
        loading: true,
        ls: true
      });
      that.findUser();
    }
  },


  getList: function () {
    //获取论坛信息
    var that = this;
    that.setData({
      loading: false,
      canIUse: false,
      ls: false
    })
    if (app.globalData.isGoBack) {
      //页面返回
      that.setData({
        index: -1, //第几条
        length: 10,
        total: 0,
        adviserList: [],
      })
      var index = that.data.index;
      var length = that.data.length;
    } else {
      var index = that.data.index;
      var length = that.data.length;
    }
    if (index <= that.data.total) {
      console.log(app)
      index++;
      common.ajaxPost(
        'portal/wlpForum/queryWlpForumList.action', {
          start: index,
          length: length,
          bid: app.globalData.bid,
          userId: app.globalData.forumUserInf.id,
          forumType: that.data.forumType
        },
        function (res) {
          if (res && res.length > 0) {
            var list = that.data.adviserList;
            list = list.concat(res.data);
            for (var i = 0; i < list.length; i++) {
              if (list[i].images) {
                //图片存在
                var images = list[i].images.split(';');
                var imagesLength = images.length;
                if (imagesLength > 3) {
                  images = images.slice(0, 3)
                }
                list[i]['images'] = images;
                list[i]['imagesLength'] = imagesLength;
              }
            }
            that.setData({
              adviserList: list,
              total: res.recordsTotal,
              index: that.data.index + res.length,
              loading: false,
              canIUse: false,
            });
            that.queryMultipleNodes(".select_item", 'selectItemHeight');
            if (res.recordsTotal == 0) {
              wx.showToast({
                title: '暂无数据',
                icon: 'none'
              })
            }
          }
        }
      )
    } else {
      wx.showToast({
        title: '没有更多了',
        icon: 'none'
      })
    }
  },

  onReachBottom: function () {
    if (app.globalData.isGoBack == true) {
      app.globalData.isGoBack = false
    }
    this.getList();
  },
  onShareAppMessage: function (res) {
    var that = this;
    var xcxids = app.globalData.queryWlpXcxByParams[0].id
    console.log('/pages/index/index?type=forum&bid=' + app.globalData.bid + "&isIndex=1" + "&xcxid=" + xcxids + "&lpid=" + app.globalData.lpid)
    return {
      title: '论坛' ,
     // + '/pages/index/index?type=forum&bid=' + app.globalData.bid + "&isIndex=1" + "&xcxid=" + xcxids + "&lpid=" + app.globalData.lpid,
      path: '/pages/index/index?type=forum&bid=' + app.globalData.bid + "&isIndex=1" + "&xcxid=" + xcxids + "&lpid=" + app.globalData.lpid,
      success: function (res) {
        // 转发成功
        console.log(2)
        app.globalData.isGoBack = true;
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onUnload: function () {
    app.globalData.isShareBack = true
    console.log("order退出了")
  },
  onHide: function () {
    app.globalData.isGoBack = true
    this.getFields();
    console.log("order退出了")
  },

  findUser: function () {
    var that = this;
    console.log(app.globalData.xcxOpenId);
    //查询用户信息
    common.ajaxPost(
      'portal/wlpUsers/queryWlpUsersForForum.action', {
        xcxOpenId: app.globalData.xcxOpenId,
        bid: app.globalData.bid
      },
      function (res) {
        console.log("获取用户信息");
        console.log(res);
        if (res.resultMsg == "操作成功" && res.resultCode == "1") {
          console.log("赋值")
          app.globalData.forumUserInf = res.data;
          console.log(app);
          //先获取banner类型

          that.queryWlpAdvisoryBannerList();


          // that.queryWlpForumTypeList();
          //that.getList();
        } else {
          that.modifyUser();
        }
      }
    )
  },

  modifyUser: function () {
    //保存用户信息
    var that = this;
    common.ajaxPost(
      'portal/wlpUsers/modifyUser.action', {
        userType: 2,
        headImage: app.globalData.userInfo.avatarUrl,
        name: app.globalData.userInfo.nickName,
        bid: app.globalData.bid,
        xcxOpenId: app.globalData.xcxOpenId,
      },
      function (res) {
        if (res && res["result"]) {
          if (res.resultMsg == '操作成功') {
            //添加成功，显示列表页
            that.setData({
              canIUse: false,
              loading: false,
              ls: false
            });

            that.queryWlpAdvisoryBannerList();
            //that.queryWlpForumTypeList()
            //that.getList();
          } else {
            //添加失败，显示loading页
            that.setData({
              canIUse: false,
              loading: true,
              ls: true
            });
          }
        }
      }
    )
  },

  queryWlpForumTypeList: function () {
    //获取帖子类型
    var that = this;
    common.ajaxPost(
      '/portal/wlpForumType/queryWlpForumTypeList.action', {
        bid: app.globalData.bid,
        status: 1
      },
      function (res) {
        console.log(res);
        if (res.result) {
          if (res.list.length > 0) {
            //有列表标签信息
            var forumTypeList = res.list;
            var forumFirst = {};
            forumFirst['bid'] = 1;
            forumFirst['id'] = -1;
            forumFirst['name'] = "全部";
            forumTypeList.unshift(forumFirst);
            that.setData({
              forumTypeList: forumTypeList
            })
            wx.setStorage({
              key: "forumTypeList",
              data: that.data.forumTypeList
            })

            //that.getList();
            // that.getInformation();
          } else {
            wx.showToast({
              title: '暂无数据',
              icon: 'none'
            })
          }
        }
      }
    )
  },

  //点赞
  changeIcon: function (e) {
    var forumIndex = e.currentTarget.dataset.forumindex;
    var that = this;
    var forumId = e.currentTarget.dataset.forumid;
    common.ajaxPost(
      '/portal/wlpForumPraise/addWlpForumPraise.action', {
        bid: app.globalData.bid,
        forumId: forumId,
        userId: app.globalData.forumUserInf.id,
        userName: app.globalData.forumUserInf.name,
        userHeadImg: app.globalData.forumUserInf.headImage
      },
      function (res) {
        console.log(res);
        if (res.resultCode == "0") {
          wx.showToast({
            title: '点赞成功',
            icon: 'none'
          });
          var up = "adviserList[" + forumIndex + "].hasPraise"; //先用一个变量，把(info[0].gMoney)用字符串拼接起来
          var up2 = "adviserList[" + forumIndex + "].praisenum";
          var up3 = that.data.adviserList[forumIndex].praisenum + 1
          that.setData({
            [up]: 1,
            [up2]: up3
          })
        }
      }
    )
  },
  //发帖子
  gotosendForum: function () {
    var that = this;
    wx.setStorage({
      key: "activeIndex",
      data: (that.data.indexs == '' ? 0 : that.data.indexs)
    })
    wx.navigateTo({
      url: '../sendForum/sendForum',
    })
  },

  //帖子详情
  gotoForumDetail: function (e) {
    this.getFields()
    //需要携带帖子id号 
    var forumid = e.currentTarget.dataset.forumid;
    wx.navigateTo({
      url: '../forumDetail/forumDetail?forumid=' + forumid + "&xcxid=" + app.globalData.queryWlpXcxByParams[0].id,
    })
  },

  //判断是资讯还是论坛
  selectIndex: function (e) {
    var that = this;
    var indexs = e.currentTarget.dataset.selectindex;

    //清空数据。
    that.setData({
      index: -1, //第几条
      length: 10,
      total: 0, //共多少条
      adviserList: [],
    })

   
    that.setData({
      isInfo: false,
      selectIndex: indexs,
    })
    that.queryWlpForumTypeList();
    that.getList();

    // if (indexs == "0") {
    //   that.setData({
    //     isInfo: true,
    //     selectIndex: indexs
    //   })
    //   that.getInformation();
    // } else {
    //   if (app.globalData.xcxtype.isShow == "1") {
    //     that.setData({
    //       isShow: true
    //     })
    //   } else {
    //     that.setData({
    //       isShow: false
    //     })
    //   }
    //   that.setData({
    //     isInfo: false,
    //     selectIndex: indexs,
    //   })
    //   that.queryWlpForumTypeList();
    //   that.getList()
    // }
  },

  tapActive: function (e) {
    var that = this;
    var indexs = e.currentTarget.dataset.indexs;
    console.log(indexs)
    wx.setStorage({
      key: "activeIndex",
      data: e.currentTarget.dataset.indexs
    })
    that.setData({
      currentTab: indexs,
      indexs: indexs,
    });
    var forumT = (indexs == 0 ? -1 : that.data.forumTypeList[indexs].id);
    console.log("数据id=" + forumT);
    var bannerHeight = that.data.bannerHeight;
    that.setData({
      forumType: forumT,
      adviserList: [],
      index: -1, //第几条
      length: 10,
      total: 0,
      scrollTop: bannerHeight
    })
    // //调用列表
    that.getList();

  },




  queryMultipleNodes: function (className, dataName) {
    var query = wx.createSelectorQuery();
    //选择id
    var that = this;
    query.select(className).boundingClientRect(function (rect) {
      // console.log(rect.width)
      var param = {};
      var string = dataName;
      param[string] = rect.height
      that.setData(param);
    }).exec();
  },



  getDomHeight: function () {
    //获取各个元素高度
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var windowHeight = res.windowHeight;
        that.setData({
          windowHeight: windowHeight
        });
      }
    });
    that.queryMultipleNodes(".swiper-block", "bannerHeight");
    that.queryMultipleNodes(".select_item", 'selectItemHeight');
    that.queryMultipleNodes(".information_content", "infContentHeight");
    that.queryMultipleNodes(".list_main", "listMainHeight")

  },

  gotozxDetail: function (e) {
    //跳转到资讯详情页
    console.log(e);
    var id = e.currentTarget.dataset.id;
    common.addPvNum(id);
    console.log(id);
    wx.navigateTo({
      url: '../zxDetail/zxDetail?id=' + id,
    })
  },


  queryWlpAdvisoryBannerList: function () {
    //获取帖子类型
    var that = this;
    common.ajaxPost(
      'portal/wlpAdvisoryBanner/queryWlpAdvisoryBannerList.action', {
        bid: app.globalData.bid,
      },
      function (res) {
        console.log(res);
        if (res.list.length > 0) {
          //有列表标签信息
          var bannerLists = res.list;
          var newBannerLists = [];
          for (var i = 0; i < bannerLists.length; i++) {
            newBannerLists.push(bannerLists[i])
          }
          that.setData({
            bannerLists: newBannerLists,
            indicatorDots: false,
            autoplay: true,
            interval: 3000,
            duration: 1000,
            swiperIndex: 0,
            circular: true,
          })
          // that.getInformation();
        } else {
          var mrbannerList = [
            'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',

            'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',

            'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
          ];
          that.setData({
            bannerLists: mrbannerList,
            indicatorDots: false,
            autoplay: true,
            interval: 3000,
            duration: 1000,
            swiperIndex: 0,
            circular: true,
          })
        }
        var indexs = that.data.selectIndex;
        that.setData({
          isInfo: false,
          selectIndex: indexs
        })
        that.queryWlpForumTypeList();
        that.getList();
        that.getDomHeight();
        //
        // if (indexs == "0") {
        //   that.setData({
        //     isInfo: true,
        //     selectIndex: indexs
        //   })
        //   that.getInformation();
        // } else {
        //   that.setData({
        //     isInfo: false,
        //     selectIndex: indexs
        //   })
        //   that.queryWlpForumTypeList();
        //   that.getList()
        // }

        //that.getInformation();
      }
    )
  },

  gotoLink: function (e) {
    //banner链接跳转
    console.log(e);
    var urlLink = e.currentTarget.dataset.linkurl;
    console.log(urlLink)
    if (urlLink == undefined || urlLink == '') {
      return false;
    } else {
      wx.navigateTo({
        url: '/pages/webView3/webView3?linkurl=' + urlLink,
      })
    }
  },


  getInformation: function () {
    //获取资讯信息
    var that = this;
    that.setData({
      loading: false,
      canIUse: false,
      ls: false
    });

    if (app.globalData.isGoBack) {
      //页面返回
      that.setData({
        index: -1, //第几条
        length: 10,
        total: 0,
        adviserList: [],
      })
      var index = that.data.index;
      var length = that.data.length;
    } else {
      var index = that.data.index;
      var length = that.data.length;
    }
    if (index <= that.data.total) {
      index++;
      common.ajaxPost(
        'portal/wlpAdvisory/queryWlpAdvisoryPageList.action', {
          start: index,
          length: length,
          bid: app.globalData.bid,
        },
        function (res) {
          console.log(res);
          if (res && res.length > 0) {
            var list = that.data.adviserList;
            list = list.concat(res.data);
            that.setData({
              adviserList: list,
              total: res.recordsTotal,
              index: that.data.index + res.length,
              loading: false,
              canIUse: false,
            })
            if (res.recordsTotal == 0) {
              wx.showToast({
                title: '暂无数据',
                icon: 'none'
              })
            }
          } else {
            wx.showToast({
              title: '没有更多了',
              icon: 'none'
            })
          }
        }
      )
    }
    that.getDomHeight();
  },
  changeTab: function (e) {
    var url = e.currentTarget.dataset.url;
    wx.switchTab({
      url: url
    })
  },
  getFields: function () {
    var that = this;
    wx.createSelectorQuery().select('#scrollView').fields({
      dataset: true,
      size: true,
      scrollOffset: true,
      properties: ['scrollX', 'scrollY']
    }, function (res) {
      console.log(res)
      that.setData({
        scrollTop: res.scrollTop
      })
      // res.dataset    // 节点的dataset
      // res.width      // 节点的宽度
      // res.height     // 节点的高度
      // res.scrollLeft // 节点的水平滚动位置
      // res.scrollTop  // 节点的竖直滚动位置
      // res.scrollX    // 节点 scroll-x 属性的当前值
      // res.scrollY    // 节点 scroll-x 属性的当前值
    }).exec()
  }
})